<style lang="less">
    @import "../carDealer.less";
    .s1{
        .ivu-select-dropdown-list {
            height:200px
        }
        width: 200px;
    }
</style>
<template>
    <ApplyListTemplate applyListClass="directCarDealerList">
        <template slot="applyQueryForm">
            <Form ref="searchForm" :model="searchForm" inline :label-width="120" class="search-form rui-query-form">
                <div class="applyQuerySearchRow">
                    <div class="applyQueryHead"></div>
                    <div class="applyQuerySearchItem">
                        <FormItem prop="channelFullName">
                            <div>
                                <Select v-model="searchForm.channelFullName" placeholder="车商名称" clearable @on-change="handleSearch" prefix="ios-search">
                                    <Option v-for="(item,k1) in cardealerNameData" :value="item" :label="item"  :key="k1"></Option>
                                </Select>
                                <a :style="{display:'block',width:'40px',lineHeight: '24px',marginLeft: '16px'}"  @click="dropDown">
                                    {{dropDownContent}}
                                    <Icon :type="dropDownIcon"></Icon>
                                </a>
                            </div>
                        </FormItem>
                    </div>
                </div>
                <div v-if="drop" class="applyQuerySearchMore table-card">
                    <div  class="applyQuerySearchMoreRow">
                        <div class="rui-query-form-item">
                            <Form-item label="法人名称" prop="legalPerson" >
                                <Input type="text" v-model.trim="searchForm.legalPerson" clearable placeholder="请输入"
                                       class="w200"/>
                            </Form-item>
                        </div>
                        <div class="rui-query-form-item">
                            <Form-item label="城市经理" prop="customerManager" >
                                <Select v-model="searchForm.customerManager" clearable placeholder="请选择"  filterable class="s1">
                                    <Option v-for="(item,k1) in userData" :value="item.username" :label="item.userRealName"  :key="k1"></Option>
                                </Select>
                            </Form-item>
                        </div>
                        <div class="rui-query-form-item">
                            <Form-item label="业务类型" prop="businessType">
                                <Select v-model="searchForm.businessType" clearable placeholder="请选择" class="w200">
                                    <Option value="01">新车</Option>
                                    <Option value="02">二手车</Option>
                                </Select>
                            </Form-item>
                        </div>
                        <div class="rui-query-form-item">
                            <Form-item label="状态" prop="channelStatus" >
                                <Select v-model="searchForm.channelStatus" placeholder="请选择" clearable  class="w200">
                                    <Option value="00">启用</Option>
                                    <Option value="01">审核中</Option>
                                    <Option value="02">草稿</Option>
                                    <Option value="03">退回</Option>
                                    <Option value="04">拒绝</Option>
                                    <Option value="05">停用</Option>
                                </Select>
                            </Form-item>
                        </div>
                    </div>
                    <div style="text-align: center">
                        <Button @click="handleSearch" type="primary">查询</Button>
                        <Button @click="handleReset">重置</Button>
                    </div>
                </div>
            </Form>
        </template>
        <template slot="applyQueryBtn">
            <Button class="btn" size="default" @click="addDirectCarDealer">新增直营车商</Button>
            <Button class="btn" size="default" @click="editCustomerManager">城市经理批量修改</Button>
            <Button class="btn" size="default" type="error" @click="disable">批量停用</Button>
            <circleLoading v-if="operationLoading"/>
        </template>
        <template slot="applyQueryTable">
            <Table :loading="loading" :columns="columns" :data="data" sortable="custom"
                   @on-sort-change="changeSort" @on-selection-change="showSelect" ref="selection">

                <template slot-scope="{ row, index }" slot="carDealerName" >
                    <a @click="checkCarDealer(row)" style="color: blue;">{{row.channelFullName}}</a>
                </template>

                <template slot-scope="{ row, index }" slot="address">
                    <span>{{getDetailAddress2(row.channelProvince,row.channelCity,row.channelAddress)}}</span>
                </template>

                <template slot-scope="{ row }" slot="carDealType" >
                    <span>{{row.carDealType =="0" ? "汽贸":"4S店"}}</span>
                </template>

                <template slot-scope="{ row, index }" slot="businessType" >
                    <span>{{getBusinessType(row.businessType)}}</span>
                </template>
                <template slot-scope="{ row, index }" slot="customerManager" >
                                <span>
                                    {{getUserRealName(row.customerManager,"01")}}</span>&nbsp;<span>{{getUserRealName(row.customerManagerOld,"02")}}</span>
                </template>

                <template slot-scope="{ row,  }" slot="channelStatus">
                    <div v-if="row.status == '00'">
                        <Tag color="success" size="default">启用</Tag>
                    </div>
                    <div v-if="row.status == '01'">
                        <Tag color="warning" size="default">审核中</Tag>
                    </div>
                    <div v-if="row.status == '02' || row.status == '06' ">
                        <Tag color="default" size="default">草稿</Tag>
                    </div>
                    <div v-if="row.status == '03'">
                        <Tag color="warning" size="default">退回</Tag>
                    </div>
                    <div v-if="row.status == '04'">
                        <Tag color="error" size="default">拒绝</Tag>
                    </div>
                    <div v-if="row.status == '05'">
                        <Tag color="error" size="default">停用</Tag>
                    </div>
                </template>

                <div slot-scope="{ row }" slot="action" class="btn-no-border">
                                <span v-if="row.status=='02' || row.status=='06' || row.status=='05' || row.status=='03'">
                                    <Button style="margin-right:5px" type="primary" size="small" @click="edit(row)" ghost>编辑</Button>
                                </span>
                    <span v-if="row.status!='02' && row.status!='06' && row.status!='05' && row.status!='03'">
                                    <Button disabled style="margin-right:5px" type="primary" size="small" @click="edit(row)" ghost>编辑</Button>
                                </span>
                    <span v-if="row.status=='02' || row.status=='06' ">
                                    <Button type="error" size="small" @click="remove(row)" ghost>删除</Button>
                                </span>
                    <span v-if="row.status!='02' && row.status!='06' ">
                                    <Button disabled type="error" size="small" @click="remove(row)" ghost>删除</Button>
                                </span>
                </div>

            </Table>
        </template>
        <template slot="applyQueryPage">
            <Page :current="searchForm.pageNumber" :total="total" :page-size="searchForm.pageSize"
                  @on-change="changePage" @on-page-size-change="changePageSize" :page-size-opts="[10,20,50]"
                  size="small" show-total show-elevator show-sizer></Page>
        </template>
        <template slot="applyQueryMore">
            <!--批量修改业务员-->
            <Modal title="请选择修改后的城市经理" v-model="modal12" :mask-closable='false' :width="400" :styles="{top: '100px'}">
                <Form  ref="editForm" :model="editForm">
                    <Form-item label="新车城市经理"  prop="customerManager"  style="widtht: 350px">
                        <Select  placeholder="请选择" v-model="editForm.customerManager" filterable class="s1" style="widtht: 200px" >
                            <Option v-for="(item,index) in customerManagerData" :value="item.username" :label="item.userRealName" :key="index" >
                            </Option>  
                        </Select>
                    </Form-item>


                    <Form-item label="二手车城市经理"  style="widtht: 300">
                        <Select  placeholder="请选择" v-model="editForm.customerManagerold" filterable class="s1" style="widtht: 200px">
                            <Option v-for="(item,index) in customerManagerDataOld" :value="item.username" :label="item.userRealName" :key="index">
                            </Option>  
                        </Select>
                    </Form-item>
                </Form>
                <div slot="footer" style="text-align:center;" >
                    <Button type="text" @click="cancelSalesMan">取消</Button>
                    <Button type="primary" @click="okSalesMan">提交</Button>
                </div>
            </Modal>
        </template>
    </ApplyListTemplate>
</template>

<script>
    import {
        bulkEditingCustomerManagerFromApply,
        bulkEditingCustomerManagerFromApplyToCase,
        getDirectCarDealerData,
        deleteCardealer,
        disableDirectCarDealer,
        getChannelInfoData,
        disableDirectCarDealerFromCase,
        getAllSaleManByChannelId,
        getAllCardealerName,
        getChannelBaseInfo,
        getAllSaleMenByChannelId
    } from "@/projects/afs-apply/api/car-dealer/dealer";
    import circleLoading from "_c/circle-loading/circle-loading.vue";
    import {getLocation} from "_p/afs-apply/api/apply-report/personal/common";
    import {province, city, area} from "_p/afs-apply/assets/js/staticData.js";
   // import {getCarBrandById,getChannelBasicInfoById} from  "@/projects/afs-channel/api/dealer/dealer";
    import {getChannelId } from "@/projects/afs-apply/api/register-mng/listRecord";
    import ApplyListTemplate from "_p/afs-apply/pages/common/ApplyListTemplate";

    export default {
        name: "DirectCarDealer-manage",
        components: {
            ApplyListTemplate,
            circleLoading
        },
        data() {

            return {
                userData:[],
                //修改城市经理
                editForm:{
                    customerManager:"",
                    customerManagerold:"",
                },
                modal12: false,
                newCarSwitch: "01",
                OldCarSwitch: "01",
                customerManagerData:[],
                customerManagerDataOld:[],
                loading: false,
                channels:[],
                operationLoading: false,
                drop: false,
                dropDownContent: "展开",
                dropDownIcon: "ios-arrow-down",
                selectCount: 0,
                selectList: [],
                selectDep: [],
                department: [],
                searchKey: "",
                searchForm: {
                    channelId:"",
                    channelName: "",
                    associAccount:"",
                    channelFullName: "",
                    legalPerson: "",
                    customerManager: "",
                    businessType: "",
                    channelBelong: "",
                    pageNumber: 1,
                    pageSize: 10,
                    startDate: "",
                    endDate: "",
                    channelStatus: "",
                },
                status:"00",
                selectDate: null,
                modalTitle: "",

                //省市
                province:[],
                city:[],
                columns: [
                    {
                        type: "selection",
                        minWidth: 60,
                        maxWidth:60,
                        align: "center",
                        fixed: "left"
                    },
                    {
                        type: 'index',
                        title:"序号",
                        minWidth: 80,
                        align: "center",
                        fixed: "left"

                    },

                    {
                        title: "车商名称",
                        minWidth: 120,
                        slot: "carDealerName",
                        fixed: "left"
                    },
                    {
                        title: "实际控制人",
                        key: "actualController",
                        minWidth: 120,
                        align: "center",
                        //sortable: true
                    },
                    {
                        title: "法人",
                        key: "legalPerson",
                        minWidth: 120,
                        align: "center",
                    },
                    {
                        title: "法人电话",
                        key: "legalPersonTel",
                        minWidth: 115,
                        align: "center",
                    },

                    {
                        title: "车商类型",
                        slot: "carDealType",
                        minWidth: 100,
                        align: "center",
                        //sortable: true

                    },
                    {
                        title: "主营品牌",
                        key: "mainBrand",
                        minWidth: 200,
                        ellipsis:true,
                        render: (h, params) => {
                            return h('div', [
                                h('span', {
                                    style: {
                                        display: 'inline-block',
                                        width: '100%',
                                        overflow: 'hidden',
                                        textOverflow: 'ellipsis',
                                        whiteSpace: 'nowrap'
                                    },
                                    domProps: {
                                        title: params.row.mainBrand
                                    }
                                }, params.row.mainBrand)
                            ])
                        }
                    },
                    {
                        title: "业务类型",
                        slot: "businessType",
                        minWidth: 120,
                        align: "center",
                        //sortable: true,

                    },
                    {
                        title: "城市经理",
                        slot: "customerManager",
                        minWidth: 120,
                        align: "center",
                        //sortable: true,

                    },
                    {
                        title: "注册时间",
                        key: "registrationDate",
                        minWidth: 120,
                        align: "center",
                        //sortable: true,
                    },
                    {
                        title: "统一社会信用代码",
                        key: "socUniCrtCode",
                        minWidth: 200,
                        align: "center",
                        //align: "center",

                    },
                    {
                        title: "注册地址",
                        slot: "address",
                        minWidth: 250
                        //sortable: true,

                    },
                    {
                        title: "状态",
                        slot: "channelStatus",
                        minWidth: 100,
                        align: "center",
                        //sortable: true,

                    },
                    {
                        title: "审批备注",
                        key: "approveRemark",
                        minWidth: 200,
                        ellipsis:true,
                        render: (h, params) => {
                            return h('div', [
                                h('span', {
                                    style: {
                                        display: 'inline-block',
                                        width: '100%',
                                        overflow: 'hidden',
                                        textOverflow: 'ellipsis',
                                        whiteSpace: 'nowrap'
                                    },
                                    domProps: {
                                        title: params.row.approveRemark
                                    }
                                }, params.row.approveRemark)
                            ])
                        }
                    },
                    {
                        title: "操作",
                        key: "action",
                        minWidth: 200,
                        align: "center",
                        fixed: "right",
                        slot: "action"
                    }

                ],
                data: [],
                cardealerNameData: [],
                total: 0
            };
        },
        methods: {
            init() {
                this.handleSearch();
                this.getProvinceData();
                this.getCityData();
              //  this.getAllDirectCardealerName();
            },


            changePage(v) {
                this.searchForm.pageNumber = v;
                this.getCarDealerList();
                this.clearSelectAll();
            },
            changePageSize(v) {
                this.searchForm.pageSize = v;
                this.getCarDealerList();
            },

            selectDateRange(v) {
                if (v) {
                    this.searchForm.startDate = v[0];
                    this.searchForm.endDate = v[1];
                }
            },

            getCarDealerList() {
                // 多条件搜索直营车商列表
                this.loading = true;
                getChannelId({}).then(res => {
                    if (res.code === "0000") {
                        this.searchForm.channelId = res.data;
                        //获取城市经理
                        this.getAllSaleManByChannelId();
                        getChannelBaseInfo(this.searchForm.channelId).then(res => {
                            if (res.code === "0000") {
                                this.searchForm.channelName = res.data[0].channelFullName;
                            }
                        });
                        //获取全部车商的名称
                        getAllCardealerName({cardealerType:"02",channelId:this.searchForm.channelId}).then(res => {
                            if (res.code === "0000") {
                                this.cardealerNameData = res.data;
                            }
                        });

                        let param={
                            channelName: this.searchForm.channelName.replace(/\s*/g,""),
                            associAccount:"",
                            channelFullName: this.searchForm.channelFullName,
                            legalPerson: this.searchForm.legalPerson.replace(/\s*/g,""),
                            customerManager: this.searchForm.customerManager,
                            businessType: this.searchForm.businessType,
                            channelBelong: this.searchForm.channelBelong,
                            pageNumber: this.searchForm.pageNumber,
                            pageSize: this.searchForm.pageSize,
                            startDate: this.searchForm.startDate,
                            endDate: this.searchForm.endDate,
                            channelStatus: this.searchForm.channelStatus,
                            channelId:this.searchForm.channelId,
                        }


                        getDirectCarDealerData(param).then(res => {
                            this.loading = false;
                            if (res.code === "0000") {
                                this.data = res.data.records;
                                this.data.forEach(function (e) {
                                    if(e.channelStatus == ''){
                                        e.channelStatus=e.channelStatusOldCar
                                    }
                                });
                                this.total = res.data.total;
                                console.log(res.data)
                                //获取业务员
                              //  this.getUserData();
                            }
                        });

                        //获取业务员
                        getAllSaleMenByChannelId(this.searchForm.channelId).then(res => {
                            if (res.code === "0000") {
                                this.userData = res.data;
                            }
                        });
                    }
                })
            },
            handleSearch() {
                this.searchForm.pageNumber = 1;
                this.getCarDealerList();
            },

            handleReset() {
                this.$refs.searchForm.resetFields();
                this.selectDate = null;
                this.searchForm.startDate = "";
                this.searchForm.endDate = "";
                this.selectDep = [];
                this.searchForm.deptId = "";
            },
            changeSort(e) {
                this.searchForm.sort = e.key;
                this.searchForm.order = e.order;
                if (e.order === "normal") {
                    this.searchForm.order = "";
                }
                this.getCarDealer();
            },
            addDirectCarDealer() {
                let param = {
                    type: '1',
                    infoView:1,
                };
                this.afs.newTab(
                    this,
                    'projects/afs-apply/pages/car-dealer/direct-car-dealer/directCarDealerIndex',
                    '直营车商新增',
                    'ios-add',
                    param,
                    'direct-cardealer-add',
                    [],
                    true);
            },

            checkCarDealer(v) {

                let param={
                    //按钮是否隐藏：保存、提交、隐藏，返回、黑名单展示
                    bottonView:1,
                    //信息是否只读:1 只读
                    infoView:0,
                    //操作类型：1，查看
                    operationType:2,
                    //车商id
                    channelId:v.id,
                    type:"0",
                    oldChannelId:v.channelId
                };
                this.afs.newTab(
                    this,
                    'projects/afs-apply/pages/car-dealer/direct-car-dealer/directCarDealerIndex',
                    '直营车商'+v.channelFullName+"查看",
                    'ios-add',
                    param,
                    'direct-cardealer-check'+v.id,
                    [],
                    true);
            },

            edit(v) {
                let param={
                    //按钮是否隐藏：保存、提交、返回展示，黑名单隐藏
                    bottonView:0,
                    //信息是否只读:1 非只读
                    infoView:1,
                    //操作类型：1，修改
                    operationType:1,
                    //直营车商id
                    channelId:v.id,
                    type: '2',
                    oldChannelId:v.channelId,
                };
                this.afs.newTab(
                    this,
                    'projects/afs-apply/pages/car-dealer/direct-car-dealer/directCarDealerIndex',
                    '直营车商'+v.channelFullName+"修改",
                    'ios-add',
                    param,
                    'direct-cardealer-edit'+v.id,
                    [],
                    true);
            },

            //根据车商id查询对应的渠道信息
            getChannelInfo(v){
              let id=v.id;
                getChannelInfoData(id).then(res => {
                    console.log(id)
                    if (res.code === "0000") {
                        this.channels=res.data
                    }
                });
            },

            remove(v) {
                this.$Modal.confirm({
                    title: "确认删除",
                    content: "您确认要删除车商 " + v.channelFullName + " ?",
                    onOk: () => {
                        this.operationLoading = true;
                        deleteCardealer(v.channelId,v.id).then(res => {
                            this.operationLoading = false;
                            if (res.code === "0000") {
                                this.$Message.success("删除成功");
                                this.handleSearch();
                            }
                        });
                    }
                });
            },

            dropDown() {
                if (this.drop) {
                    this.dropDownContent = "展开";
                    this.dropDownIcon = "ios-arrow-down";
                } else {
                    this.dropDownContent = "收起";
                    this.dropDownIcon = "ios-arrow-up";
                }
                this.drop = !this.drop;
            },
            showSelect(e) {
                this.selectList = e;
                this.selectCount = e.length;
            },

            //停用车商
            disable() {
                if (this.selectCount <= 0) {
                    this.$Message.warning("您还未选择要停用的车商");
                    return;
                }
                let status = false;
                this.selectList.forEach(function (e) {
                    if(e.status != '00'){
                        status = true;
                    }
                });
                if(status){
                    this.$Message.warning("只能停用已启用的车商");
                    return;
                }
                this.$Modal.confirm({
                    title: "确认停用",
                    content: "您确认要停用所选的 " + this.selectCount + " 条数据?",
                    onOk: () => {
                        let ids = [];
                        this.selectList.forEach(function (e) {
                            ids += e.id + ",";
                        });
                        ids = ids.substring(0, ids.length - 1);
                        this.operationLoading = true;
                        //禁用方法
                        disableDirectCarDealer(ids,this.searchForm.channelId,"05").then(res => {
                            this.operationLoading = false;
                            if (res.code === "0000") {
                                this.$Message.success("停用成功");
                            }
                        });
                    }
                });
            },

            //批量修改业务员
            editCustomerManager() {
                if (this.selectCount <= 0) {
                    this.$Message.warning("您还未选择要修改的数据");
                    return;
                }
                //置空城市经理
                this.editForm.customerManager="";
                this.editForm.customerManagerold=""

                let editStatus = false;
                const s = new Set();
                this.selectList.forEach(function (e) {
                    if(e.status != '00' && e.status != '05'){
                        editStatus = true;
                    }
                });
                if(editStatus){
                    this.$Message.warning("只能修改停用或已启用的车商的城市经理");
                    return;
                }
                this.modal12=true;
                this.getAllSaleManByChannelId();

            },
            getAllSaleManByChannelId(){
                let channelId = this.searchForm.channelId;
                let newCar ="01";
                let oldCar ="02";
                getAllSaleManByChannelId(channelId,newCar).then(res => {
                    if (res.code === "0000") {
                        this.customerManagerData=res.data;
                    }
                });
                getAllSaleManByChannelId(channelId,oldCar).then(res => {
                    if (res.code === "0000") {
                        this.customerManagerDataOld=res.data;
                    }
                });
            },

            okSalesMan(){
                let ids = [];
                this.selectList.forEach(function (e) {
                    ids.push(e.id);
                });
                //新车
                if(this.editForm.customerManager){
                    let params = {
                        businessType:"01",
                        salesman:this.editForm.customerManager,
                        channelId: this.searchForm.channelId,
                        allCarDealerIds:ids,
                    }
                    bulkEditingCustomerManagerFromApply(params).then(res => {
                    });
                }
                //二手车
                if(this.editForm.customerManagerold){
                    let oldParams = {
                        businessType:"02",
                        salesman:this.editForm.customerManagerold,
                        channelId: this.searchForm.channelId,
                        allCarDealerIds:ids,
                    }
                    bulkEditingCustomerManagerFromApply(oldParams).then(res => {
                    });
                }

                if(!this.editForm.customerManagerold && !this.editForm.customerManager){
                    this.$Message.error("请选择需要修改的城市经理!");
                    this.operationLoading = false;
                    return false;
                }

                this.operationLoading = false;
                this.$Message.success("修改成功");
                this.handleSearch();
                this.modal12=false;
            },
            cancelSalesMan(){
                this.modal12=false;
            },

            //反向解析省市地址
            getProvinceData() {
                let param = {level:"1",upperCode: "1"};

                getLocation(param).then(res => {
                    if(res.code === "0000"){
                        this.province=res.data;
                    }
                });
            },
            getCityData() {
                let param = {level:2,upperCode:''};
                getLocation(param).then(res => {
                    if (res.code == "0000") {
                        this.city=res.data;
                    }
                });
            },
            getDetailAddress2(registeredProvince,registeredCity,registeredAddress){
                if(registeredProvince!="" && registeredCity!="" && registeredAddress !=""){
                    let province="";
                    let city="";
                    for(let i=0;i<this.province.length;i++){
                        if(this.province[i].value==registeredProvince){
                            province=this.province[i].label;
                        }
                    };
                    for(let i=0;i<this.city.length;i++){
                        if(this.city[i].value==registeredCity){
                            city=this.city[i].label;
                        }
                    };
                    return province+city+registeredAddress;
                }else{
                    return '';
                }
            },
            getUserRealName(val,type){
                if(val==null ||val=="" ||val ==undefined){
                    return;
                }
                let dic = {};
                if(type == '01'){
                    this.customerManagerData.forEach(column => {
                        if(column.username === val){
                            dic = column;
                        }
                    });
                }else{
                    this.customerManagerDataOld.forEach(column => {
                        if(column.username === val){
                            dic = column;
                        }
                    });
                }
                return dic.userRealName;
            },
            getUserData(){
                this.userData=[]
                var userSet = new Set();
                var userData = new Set();
                this.customerManagerData.forEach(column => {
                    userData.add(column);
                });
                this.customerManagerDataOld.forEach(column => {
                    userData.add(column);
                });
                this.data.forEach(item=>{
                    if(item.customerManager){
                        userSet.add(item.customerManager)
                    }
                    if(item.customerManagerOld){
                        userSet.add(item.customerManagerOld)
                    }
                })
                if(userSet){
                    userSet.forEach(item=>{
                        userData.forEach(column => {
                            if(column.username === item){
                                this.userData.push(column)
                            }
                        });
                    })
                }
            },
            getBusinessType(val){
                if(!val){
                    return "";
                }else{
                    if(val.indexOf("01") > -1 && val.indexOf("02") >-1 ) return "新车 二手车";
                    else if(val.indexOf("01")> -1 )  return "新车";
                    else if(val.indexOf("02")> -1) return "二手车";
                }
            },

        },
        mounted() {
            this.init();
        },
        watch: {
            '$route'(to,from){
                this.handleReset();
                this.handleSearch();
            }
        },
    };
</script>
